<template>
  <div class="project-exception-list-container">
    <div class="row search-row">
      <el-form ref="formRef" :model="searchForm.condition" inline label-width="auto">
        <div style="display: flex;">
          <div>
            <el-form-item label="项目编号" prop="projectNo" style="width: 21%">
          <el-input v-model="searchForm.condition.projectNo" placeholder="请输入项目编号"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName" style="width: 21%">
          <el-input v-model="searchForm.condition.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="项目单位" prop="projectCompany" style="width: 21%">
          <el-input v-model="searchForm.condition.projectCompany" placeholder="请输入项目单位"/>
        </el-form-item>
        <el-form-item label="申报单号" prop="dailyConstructionNo" style="width: 21%">
          <el-input v-model="searchForm.condition.dailyConstructionNo" placeholder="请输入申报单号"/>
        </el-form-item>
        <el-form-item label="上报时间" prop="applyTime" style="width: 30%">
          <el-date-picker v-model="searchForm.condition.applyTime" style="width: 100%;" placeholder="请选择" type="datetimerange" value-format="YYYY-MM-DD HH:mm" format="YYYY-MM-DD HH:mm" start-placeholder="开始时间"
          end-placeholder="结束时间"/>
        </el-form-item>
        <el-form-item label="描述关键词" prop="errorDesc" style="width: 21%">
          <el-input v-model="searchForm.condition.errorDesc" placeholder="请输入描述关键词"/>
        </el-form-item>
        <el-form-item label="航站楼" prop="locations">
          <el-checkbox :indeterminate="isIndeterminateLocation" v-model="checkAllLocation" @change="handleCheckAllChangeLocation">全选 {{ terminalTotal }}</el-checkbox>
          <div style="margin-left: 20px;"></div>
          <el-checkbox-group v-model="searchForm.condition.locations" @change="handleCheckedChangeLocation">
            <el-checkbox v-for="item in options.locationEnum" :label="item.value" :key="item.value">{{item.label}} {{ typeNumEnum.terminal[item.value] }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
          <el-form-item label="项目类型" prop="projectTypes">
          <el-checkbox :indeterminate="isIndeterminateProjectType" v-model="checkAllProjectType" @change="handleCheckAllChangeProjectType">全选 {{ projectTotal }}</el-checkbox>
          <div style="margin-left: 20px;"></div>
          <el-checkbox-group v-model="searchForm.condition.projectTypes" @change="handleCheckedChangeProjectType">
            <el-checkbox v-for="item in options.projectTypeEnum" :label="item.value" :key="item.value">{{item.label}} {{ typeNumEnum.projectType[item.value] }}</el-checkbox>
          </el-checkbox-group>
          </el-form-item>
          </div>
          <div style="display: flex; align-items: end; margin-bottom: 20px;">
            <el-button @click="handleReset">清空</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <div class="row table-row">
      <div class="table-head">
        <div style="display: flex; align-items: center;">
          <span>数据列表</span>
          <el-radio-group v-model="searchForm.condition.errorType" style="margin-left: 10px;" @change="typeChange">
            <el-radio-button class="state-item" :label="1" >
              违规情况
            <span class="state-num"><span>{{totalData?.violationCount}}</span></span>
          </el-radio-button>
          <el-radio-button class="state-item" :label="2" >
              异常情况
            <span class="state-num"><span>{{totalData?.abnormalCount}}</span></span>
          </el-radio-button>
            <!-- <el-badge :value="totalData?.violationCount">
              <el-radio-button :label="1">违规情况</el-radio-button>
            </el-badge> -->
            <!-- <el-badge :value="totalData?.abnormalCount">
              <el-radio-button :label="2">异常情况</el-radio-button>
            </el-badge> -->
          </el-radio-group>
        </div>
        <div>
          <el-button type="primary" @click="handleExportList">导出</el-button>
          <!-- <el-button type="primary" @click="openBeforeCreate" v-if="pageType===ProjectListType.LIST">新增</el-button> -->
        </div>
      </div>
      <el-table :data="tableData" class="project-application-table" v-loading="loading">
        <el-table-column label="序号" prop="index" width="60">
          <template v-slot="{$index}">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column min-width="120" label="项目类型" prop="projectType" :formatter="(row, column, cellValue) => dicFormatter(options.projectTypeEnumOrigin, cellValue)"/>
        <el-table-column min-width="200" label="项目名称" show-overflow-tooltip prop="projectName"/>
        <el-table-column min-width="200" label="项目编号" prop="projectNo"/>
        <el-table-column min-width="200" label="项目单位" prop="projectCompany"/>
        <el-table-column min-width="200" label="申报单号" prop="dailyConstructionNo"/>
        <el-table-column min-width="200" label="情况描述"  show-overflow-tooltip  prop="errorDesc"/>
        <el-table-column min-width="170" label="上报时间" prop="createTime"/>
        <el-table-column width="80" label="操作" fixed="right" align="center">
          <template v-slot="{row}">
            <el-button class="link-btn" link type="primary" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <HyPagination background layout="prev, pager, next" :total="searchForm.total" v-model:current-page="searchForm.pageNum"
                    @size-change="handleQuery" @current-change="getList"/>
    </div>
    <el-dialog
    v-model="dialogVisible"
    title="查看情况描述"
    :width="'50%'"
    @Cancel="dialogVisible = false"
    :defaultButton="false"
  >
    <div v-if="searchForm.condition.errorType === 1" v-for="(item,index) in tempRow?.formContent?.violations" style="max-height: 600px; overflow: scroll;">
        <div style="display: flex;line-height: 15px;">
          <div style="background: #5981EF; width: 3px; height: 15px; margin-right: 10px;"></div>
          <span style="font-weight: 600;">违规情况{{index + 1}}</span>
        </div>
        <el-form :label-width="123">
          <el-form-item label="违规情况描述：" style="width: 100%;">
            <div style="width: 80%; word-wrap: break-word;">{{item.description}}</div>
          </el-form-item>
          <el-form-item label="现场情况：">
            <div v-for="media in item.videoOrPics">
              <el-image v-if="media.type === 0" :src="media.url" loading="eager" :preview-src-list="[media.url]" style="width: 100px; height: 60px" fit="contain"></el-image>
              <video v-else :src="media.url" controls width="100%" height="100%"></video>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="searchForm.condition.errorType === 2" v-for="(item,index) in tempRow?.formContent?.abnormalities" style="max-height: 600px; overflow: scroll;">
        <div style="display: flex;line-height: 15px;">
          <div style="background: #5981EF; width: 3px; height: 15px; margin-right: 10px;"></div>
          <span style="font-weight: 600;">异常情况{{index + 1}}</span>
        </div>
        <el-form :label-width="123">
          <el-form-item label="异常情况描述：">
            <div style="width: 80%; word-wrap: break-word;">{{item.description}}</div>
          </el-form-item>
          <el-form-item label="现场情况：">
            <div v-for="media in item.videoOrPics">
              <el-image v-if="media.type === 0" :src="media.url" :preview-src-list="[media.url]" style="width: 100px; height: 60px" fit="contain"></el-image>
              <video v-else :src="media.url" controls width="100%" height="100%"></video>
            </div>
          </el-form-item>
        </el-form>
      </div>
    <!-- <template #custom>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template> -->
  </el-dialog>
  </div>
</template>

<script>
import router from '@/router'
import {
  getTotal,
  getPageList,
  exportList,
  PageListType
} from '@/api/construction/projectException'
import {getResource} from "@/api/resource";
import { cloneDeep } from 'lodash'
import {
  dicFormatter, nodeTypeEnum,
  personSourceEnum,
  personTypeEnum,
  ProjectListType,
} from "@/views/construction/project-application/projectUtil";
import EditDialog from "@/components/editDialog/index.vue";
import HyPagination from "@/views/construction/project-application/componens/HyPagination";
import {dayjs} from "element-plus";
import { ElMessage ,ElMessageBox } from 'element-plus'
import store from "@/store";
export default {
  components: { HyPagination,EditDialog},
  data() {
    return {
      pageType: ProjectListType.LIST,
      loading: false,
      dialogVisible: false,
      tempRow:undefined,
      isIndeterminateProjectType: false,
      checkAllProjectType: false,

      isIndeterminateLocation: false,
      checkAllLocation: false,

      searchForm: {
        condition:{
          errorType:1,
          projectTypes: undefined,
          locations:undefined,
        },
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableData: [],
      options: {
        companyUnitTreeData: [],
        locationEnum: [],
        projectTypeEnum: [],
        projectTypeEnumOrigin:[]
      },
      terminalTotal:0,
      projectTotal:0,
      totalData:undefined,
      terminalTotalData: undefined,
      projectTypeTotalData: undefined,
      typeNumEnum: {
        projectType: {},
        state: {},
        terminal: {}
      },
      dicFormatter,
      ProjectListType,
      fileUrl:undefined,
      showViewer:false,
    }
  },
  provide() {
    return {
      options: this.options
    }
  },
  mounted() {
    this.initOptions()
    this.getList()
  },
  methods: {
    typeChange(type){
      this.searchForm.condition.errorType = type
      this.getList()
    },
    handleCheckAllChangeProjectType(value) {
      let all = this.options.projectTypeEnum.map(item => item.value)
      this.searchForm.condition.projectTypes = value ? all : [];
      this.isIndeterminateProjectType = false;
    },
    handleCheckedChangeProjectType(value) {
      let total = this.options.projectTypeEnum.length
      let checkedCount = value.length;
      this.checkAllProjectType = checkedCount === total;
      this.isIndeterminateProjectType = checkedCount > 0 && checkedCount < total;
    },


    handleCheckAllChangeLocation(value) {
      let all = this.options.locationEnum.map(item => item.value)
      this.searchForm.condition.locations = value ? all : [];
      this.isIndeterminateLocation = false;
    },
    handleCheckedChangeLocation(value) {
      let total = this.options.locationEnum.length
      let checkedCount = value.length;
      this.checkAllLocation = checkedCount === total;
      this.isIndeterminateLocation = checkedCount > 0 && checkedCount < total;
    },
    initOptions() {
      Promise.all([
        getResource('CM_PROJECT_TYPE'),
        getResource('terminals'),
      ]).then(([
                 res1,
                 res2,
               ]) => {
        this.options.projectTypeEnum = res1.data.properties.meta
        this.options.projectTypeEnumOrigin = res1.data.properties.meta
        this.options.locationEnum = res2.data.properties.meta
        this.options.locationEnumOrigin = res2.data.properties.meta
        this.options.projectTypeEnumOrigin.push({label: "应急抢修",value: "4"})
        
        this.getTotal()
      })
    },
    async getTotal(){
      this.terminalTotal = 0
      this.projectTotal = 0
      const res = await getTotal(this.searchForm)
      this.totalData = res.data
      this.terminalTotalData = res.data.terminalCount
      let copiedObj = cloneDeep(this.options.locationEnumOrigin);
      copiedObj.forEach(item =>{
        if(this.terminalTotalData[item.value]){
          this.terminalTotal += parseInt(this.terminalTotalData[item.value])
          item.label = `${item.label} ${this.terminalTotalData[item.value]}`
        }else{
          item.label = `${item.label} 0`
        }
      })
      this.options.locationEnum = copiedObj

      this.projectTypeTotalData = res.data.projectTypeCount
      let copiedObj2 = cloneDeep(this.options.projectTypeEnumOrigin);
      copiedObj2.forEach(item =>{
        if(this.projectTypeTotalData[item.value]){
          this.projectTotal += parseInt(this.projectTypeTotalData[item.value])
          item.label = `${item.label} ${this.projectTypeTotalData[item.value]}`
        }else{
          item.label = `${item.label} 0`
        }
      })
      this.options.projectTypeEnum = copiedObj2
    },
    handleQuery() {
      this.searchForm.pageNum = 1
      this.getList()
      this.getTotal()
    },
    handleReset() {
      this.$refs.formRef.resetFields()
      this.isIndeterminateProjectType = false
      this.isIndeterminateLocation = false
      this.checkAllProjectType = false
      this.checkAllLocation = false
      this.getList()
      this.getTotal()
    },
    getList() {
      this.loading = true
      let {condition, ...more} = this.searchForm
      let {projectTypes, locations,applyTime} = this.searchForm.condition
      let newProjectType = projectTypes?.length < this.options.projectTypeEnum.length && projectTypes?.length > 0 ? projectTypes : undefined
      let newLocation = locations?.length < this.options.locationEnum.length && locations?.length > 0 ? locations : undefined
      let createTimeStart, createTimeEnd
      if (applyTime) {
        createTimeStart=applyTime[0]
        createTimeEnd=applyTime[1]
      }else{
        createTimeStart=undefined
        createTimeEnd=undefined
      }
      getPageList({
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        condition:{
          ...this.searchForm.condition,
          projectType: condition.projectTypes,
          terminalBuilding: condition.locations,
          createTimeStart,
          createTimeEnd
        }
      }).then(res => {
        let {total, list} = res.data
        this.tableData = list
        this.searchForm.total = total
      }).catch(e => {
        ElMessage.error(e || '查询失败')
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        }, 300)
      })
    },
    handleView(data) {
      this.tempRow = data
      this.dialogVisible = true
    },
    handleExportList() {
      if(!this.tableData.length){
        this.$message.error('无数据！')
        return
      }
      this.searchForm.condition.projectType = this.searchForm.condition.projectTypes
      this.searchForm.condition.terminalBuilding = this.searchForm.condition.locations
      exportList(this.searchForm.condition).then(res => {
        const link = document.createElement('a')
        const blob = new Blob([res], {type: 'application/vnd.ms-excel'})
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute(
          'download',
          `项目施工异常${dayjs().format('YYYY-MM-DD')}.xlsx`
        )
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }).catch(e => {
        ElMessage.error(e || '导出失败')
      })
    }
  },
}
</script>

<style lang="less">
.project-exception-list-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;

  .row {
    box-sizing: border-box;
    padding: 20px;
    background: white;
    margin-top: 20px;
    border-radius: 5px;
  }

  // .radio-row {
  //   display: flex;
  //   position: relative;

    .state-item {

      .state-num {
        z-index: 1;
        position: absolute;
        right: -1px;
        top: -9px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        width: 18px;
        height: 18px;
        font-size: 12px;
        background: #D9001B;
        color: white;
      }
    }
  // }

  .search-row {
    padding: 20px 20px 10px !important;
  }

  .table-row {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .table-head {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
  }

  .project-application-table {
    --el-table-header-bg-color: #F3F4F7;
    --el-table-header-text-color: #353A42;
    --el-table-row-hover-bg-color: #ebf7ff;
    --el-table-text-color: #535862;

    &.el-table--large {
      .el-table__header-wrapper {
        .el-table__cell {
          padding: 16px 0;
        }
      }

      .el-table__body-wrapper {
        .el-table__cell {
          padding: 15px 0;
        }
      }
    }
  }


  .before-create-dialog {
    display: flex;
    justify-content: space-around;

    .before-create-dialog-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 150px;
      height: 150px;
      background: #F6FCFF;
      border-radius: 10px;
      cursor: pointer;

      .before-create-dialog-item-image {
        width: 50px;
        height: 50px;
        background: red;
        margin-bottom: 20px;
      }

      .before-create-dialog-item-type {

      }
    }
  }

}
</style>
